package com.xiaoyao.mvcframework.v1.servlet;

import com.xiaoyao.mvcframework.annotation.YXAutowired;
import com.xiaoyao.mvcframework.annotation.YXController;
import com.xiaoyao.mvcframework.annotation.YXRequestMapping;
import com.xiaoyao.mvcframework.annotation.YXService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

public class YXDispatcherServlet extends HttpServlet {

    private Map<String, Object> mapping = new HashMap<String, Object>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            this.doDispatch(req, resp);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void init(ServletConfig config) {
        InputStream is = null;
        try {
            Properties configContext = new Properties();
            is = this.getClass().getClassLoader().getResourceAsStream(config.getInitParameter("contextConfigLocation").replaceAll("classpath:", ""));
            configContext.load(is);
            String scanPackage = configContext.getProperty("scanPackage");
            this.doScanner(scanPackage);
            for (String className : mapping.keySet()) {
                if (!className.contains(".")) {
                    continue;
                }
                Class<?> clazz = Class.forName(className);
                if (clazz.isAnnotationPresent(YXController.class)) {
                    this.initController(clazz, className);
                } else if (clazz.isAnnotationPresent(YXService.class)) {
                    this.initService(clazz);
                }
            }
            this.doAutowired();
        } catch (Exception e) {
        } finally {
            if (is != null) {
                try {
                    is.close();;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("YX MVC Framework is init ");
    }

    private void doAutowired() {
        mapping.values().stream().filter(o -> Objects.nonNull(o)).forEach(o -> {
            Class<?> clazz = o.getClass();
            if(clazz.isAnnotationPresent(YXController.class)){
                Field[] fields = clazz.getDeclaredFields();
                for (Field field : fields) {
                    if(!field.isAnnotationPresent(YXAutowired.class)) { continue; }
                    YXAutowired autowired = field.getAnnotation(YXAutowired.class);
                    String beanName = autowired.value();
                    if("".equals(beanName)){
                        beanName = field.getType().getName();
                    }
                    field.setAccessible(true);
                    try {
                        field.set(o, mapping.get(beanName));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void initService(Class<?> clazz) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        YXService service = clazz.getAnnotation(YXService.class);
        String beanName = service.value();
        if ("".equals(beanName)) {
            beanName = clazz.getName();
        }
        Object instance = clazz.getDeclaredConstructor().newInstance();
        mapping.put(beanName, instance);
        for (Class<?> anInterface : clazz.getInterfaces()) {
            if (mapping.containsKey(anInterface.getName())) {
                System.out.println(anInterface.getName() + ": BeanName Same");
            }
            mapping.put(anInterface.getName(), instance);
        }
    }

    private void initController(Class<?> clazz, String className) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        mapping.put(className, clazz.getDeclaredConstructor().newInstance());
        String baseUrl = "";
        if (clazz.isAnnotationPresent(YXRequestMapping.class)) {
            YXRequestMapping requestMapping = clazz.getAnnotation(YXRequestMapping.class);
            baseUrl = requestMapping.value();
        }
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (!method.isAnnotationPresent(YXRequestMapping.class)) {
                continue;
            }
            YXRequestMapping requestMapping = method.getAnnotation(YXRequestMapping.class);
            String url = (baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");
            mapping.put(url, method);
            System.out.println(String.format("Mapped %s , %s", url, method));
        }
    }

    private void doScanner(String scanPackage) {
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        File classDir = new File(url.getFile());
        for (File file : classDir.listFiles()) {
            if (file.isDirectory()) {
                this.doScanner(scanPackage + "." + file.getName());
                continue;
            }
            if (!file.getName().endsWith("class")) {
                continue;
            }
            String clazzName = (scanPackage + "." + file.getName().replace(".class", ""));
            mapping.put(clazzName, null);
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        System.out.println(" doDispatch into ");
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replace(contextPath, "").replaceAll("/+", "/");
        if (!mapping.containsKey(url)) {
            resp.getWriter().write("404 NOT FOUND");
            return;
        }
        Method method = (Method) mapping.get(url);
        Map<String, String[]> params = req.getParameterMap();
        method.invoke(mapping.get(method.getDeclaringClass().getName()), req, resp, "aa");
    }
}
